import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common';
import {Request, Response} from 'express';

// 拓展HttpException类型
class ValidationException extends HttpException {
  public validationResponse: {message: string[]}

  constructor(message: string[], status?: number) {
    super(message, status || HttpStatus.BAD_REQUEST);
    this.validationResponse = { message };
  }

  getResponse(): {message: string[]} {
    return this.validationResponse;
  }
}

type ExceptionResponseType = {message: string[]} | {message?: string};

@Catch(HttpException, ValidationException)
export class ExceptionInterceptor implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost): any {
    const context = host.switchToHttp();
    const request = context.getRequest<Request>()
    const response = context.getResponse<Response>()
    const status = exception.getStatus()

    // 类型判断
    let exceptionResponse: ExceptionResponseType
    if (exception instanceof ValidationException) {
      exceptionResponse = exception.getResponse()
    } else {
      exceptionResponse = exception.getResponse() as ExceptionResponseType
    }

    response.status(status).json({
      success: false,
      time: new Date(),
      data: Array.isArray(exceptionResponse?.message) ? exceptionResponse.message : [exception.message],
      status,
      path: request.url
    })
  }
}